package com.qjc.demo.thread.Semaphore;

import java.util.concurrent.*;

/**
 * @Description: 信号量
 * @Author: qjc
 * @Date: 2020/7/27
 */
public class SemaphoreTest {

    /**
     * Semaphore 信号量也是 Java 中的 个同步器，与CountDownLatch和CycleBarrier不
     * 同的是，它内部的计数器是递增的，并且在一开始初始Semaphore时可以指定一个初始
     * 值，但是并不需要知道需要同步的线程个数，而是在需要同步的地方调用 acquire 方法时
     * 指定需要同步的线程个数。
     */

    /**
     * 在主线程中开启两个子线程让它们执行，等所有子线程执行完毕后主线程再继续向下运行。
     */

    private static Semaphore semaphore = new Semaphore(0);


    private final static int THREAD_POOL_SIZE = 2;
    private final static long KEEP_ALIVE_TIME = 0L;

    public static void main(String[] args) throws InterruptedException {
//        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        ExecutorService executorService = new ThreadPoolExecutor(THREAD_POOL_SIZE, THREAD_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10), new ThreadPoolExecutor.AbortPolicy());

        executorService.submit(() -> {
            System.out.println(Thread.currentThread() + " over1");
            semaphore.release();
        });

        executorService.submit(() -> {
            System.out.println(Thread.currentThread() + " over2");
            semaphore.release();
        });

        //等待子线程执行完毕，返回
        semaphore.acquire(2);//传参为2说明调用 acquire 方法的线程会一直阻塞，知道信号量的计数变为2才会返回
        System.out.println("all child thread over!");


        executorService.shutdown();

    }


}
